import logging
from json import JSONDecodeError
from typing import Callable, Any

from requests import Response

from testHelper.FailedTestLog import failed_test_log, FailedTest
from utils.StringUtils import get_test_name, current_time


def skip_test(func: Callable) -> Callable:
    """
    跳过测试装饰器
    :param func:
    :return:
    """

    def wrapper():
        logging.info(f"skip {get_test_name(func.__name__)} test")

    return wrapper


def fetch(func: Callable[[], Response]) -> Callable:
    """
    自动处理一些请求后的事物
    :param func:
    :return:
    """

    def wrapper() -> Any:
        data = None
        try:
            data = func()
            if data.ok:
                return data.json()
        except ConnectionError:
            logging.error("连接失败")
            failed_test_log.add_test(FailedTest(func, current_time(), "服务器异常"))
        except JSONDecodeError:
            logging.error(f"读取{data.url}发回的请求体json失败")
            logging.error(f"测试{get_test_name(func.__name__)}失败")
            failed_test_log.add_test(FailedTest(func, current_time(), "不能正确读取返回的json"))

    return wrapper


if __name__ == "__main__":
    logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                        level=logging.DEBUG)


    @skip_test
    def account_test():
        print(1)


    account_test()
